<?php

namespace Shared\Doctrine\Mysql\StringFunction;

use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\SqlWalker;
use Doctrine\ORM\Query\Parser;

/**
 * 
 * @author Peter Yordanov <p.jordanov@object.bg>
 * @copyright (c) 2014, ASPECT.BG Ltd. (http://www.aspect.bg/)
 */
class Field extends FunctionNode {

	private $exprValues = [];

	public function getSql(SqlWalker $sqlWalker) {
		$buildSQL = 'FIELD(';
		$values = [];
		foreach ($this->exprValues as $value) {
			$values[] = $sqlWalker->walkStringPrimary($value);
		}
		$buildSQL .= implode(',', $values);
		$buildSQL .= ')';
		return $buildSQL;
	}

	public function parse(Parser $parser) {
		$parser->match(\Doctrine\ORM\Query\Lexer::T_IDENTIFIER);
		$parser->match(\Doctrine\ORM\Query\Lexer::T_OPEN_PARENTHESIS);
		while ($parser->getLexer()->isNextToken(Lexer::T_COMMA) or ! $this->exprValues) {
			if ($this->exprValues) {
				$parser->match(Lexer::T_COMMA);
			}
			$val = $parser->ArithmeticExpression();

			$this->exprValues[] = $val;
		}
		$parser->match(\Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS);
	}

}
